package com.cn.sys.main.service.impl;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.cn.sys.frame.dao.BaseSpringJdbcDao;
import com.cn.sys.frame.exception.ServiceException;
import com.cn.sys.frame.service.impl.BaseServiceImpl;
import com.cn.sys.frame.util.JsonUtil;
import com.cn.sys.frame.util.page.PageData;
import com.cn.sys.frame.util.query.QueryBean;
import com.cn.sys.frame.util.query.QueryCondition;
import com.cn.sys.main.annotation.OperationDescription;
import com.cn.sys.main.dao.SysRoleDao;
import com.cn.sys.main.dao.SysRoleFunctionDao;
import com.cn.sys.main.dao.SysRoleModuleDao;
import com.cn.sys.main.dao.SysUserRoleDao;
import com.cn.sys.main.entity.SysRole;
import com.cn.sys.main.entity.SysRoleFunction;
import com.cn.sys.main.entity.SysRoleModule;
import com.cn.sys.main.service.SysRoleService;

@Service("sysRoleService")
public class SysRoleServiceImpl extends BaseServiceImpl<SysRole, Long> implements
		SysRoleService {

	private SysRoleDao sysRoleDao;
	@Autowired
	private SysRoleModuleDao sysRoleModuleDao;
	@Autowired
	private SysUserRoleDao sysUserRoleDao;
	@Autowired
	private SysRoleFunctionDao sysRoleFunctionDao;
	
	@Autowired
	public void setBaseDao(BaseSpringJdbcDao<SysRole, Long> sysRoleDao) {
		this.baseDao = sysRoleDao;
		this.sysRoleDao = (SysRoleDao) sysRoleDao;
	}
	
	@Cacheable(value="sysRoleCache", key = "#id + 'get'")
	public SysRole get(Long id) throws Exception {
		return super.get(id);
	}

	@OperationDescription(operateType = "save", 
			content = "添加角色信息\nID:${#entity.id}\n角色名称:${#entity.roleName}\n创建时间:${#entity.createTime}", 
			operateObj = "SysRole")
	public SysRole save(SysRole entity) throws Exception {
		return super.save(entity);
	}

	@OperationDescription(operateType = "update", 
			content = "修改角色信息\nID:${#entity.id}\n角色名称:${#entity.roleName}\n修改时间:${#entity.updateTime}", 
			operateObj = "SysRole")
	@CacheEvict(value="sysRoleCache", key=" #entity.id + 'get'")
	public SysRole update(SysRole entity) throws Exception {
		return super.update(entity);
	}

	public long getCount(QueryCondition queryCondition) throws Exception {
		return super.getCount(queryCondition);
	}

	public List<SysRole> getAll() throws Exception {
		return super.getAll();
	}

	public PageData<SysRole> getPageData(PageData<SysRole> pageData,
			QueryCondition queryCondition) throws Exception {
		return super.getPageData(pageData, queryCondition);
	}

	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class, readOnly=false)
	@OperationDescription(operateType = "delete", content = "删除角色信息\nID:${#id}", operateObj = "SysRole")
	@CacheEvict(value="sysRoleCache", key=" #id + 'get'")
	public int delete(Long id) throws Exception {
		QueryCondition queryCondition = new QueryCondition();
		QueryBean qb = new QueryBean(" WHERE ROLE_ID = ?", "ROLE_ID", id);
		queryCondition.setQueryBean(qb);
		int result = 0;
		try {
			sysUserRoleDao.delete(queryCondition);
			sysRoleModuleDao.delete(queryCondition);
			sysRoleFunctionDao.delete(queryCondition);
			result = sysRoleDao.delete(id);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("删除角色出错!["+e.getMessage()+"]");
		}
		return result;
	}
	
	public List<Map<String, Object>> getRolesByUserId(String userId) throws Exception{
		if(StringUtils.isBlank(userId)){
			userId = "-1";
		}
		String sql = "SELECT T1.ID,T1.ROLE_NAME,T2.USER_ID,T2.ROLE_ID FROM SYS_ROLE T1 LEFT JOIN SYS_USER_ROLE T2 " +
				"ON T1.ID = T2.ROLE_ID AND T2.USER_ID = ? ORDER BY T1.ROLE_NAME ASC";
		List<Map<String, Object>> list = sysRoleDao.getJdbcTemplate().queryForList(sql, Long.valueOf(userId));
		return list;
	}

	public List<SysRole> getRoleListByUserId(String userId) throws Exception{
		return sysRoleDao.listBySql("SELECT T1.* FROM SYS_ROLE T1,SYS_USER_ROLE T2 WHERE T1.ID=T2.ROLE_ID AND T2.USER_ID=?", Long.valueOf(userId));
	}
	public String getModuleAndFunByRoleId(String roleId) throws Exception{
		if(StringUtils.isBlank(roleId)){
			roleId = "-1";
		}
		String sql = "SELECT T1.ID \"id\",T1.MODULE_NAME \"name\",T1.PARENT_ID \"pId\",T1.ORDER_INDEX,T3.ROLE_ID FROM SYS_MODULE T1 LEFT JOIN SYS_ROLE_MODULE T3 ON T1.ID=T3.MODULE_ID AND T3.ROLE_ID= ? WHERE T1.STATUS = '1' " +
				"UNION ALL SELECT T2.ID \"id\",T2.NAME \"name\",T2.MODULE_ID \"pId\",T2.ORDER_INDEX, T4.ROLE_ID FROM SYS_FUNCTION T2 LEFT JOIN SYS_ROLE_FUNCTION T4 ON T2.ID=T4.FUNCTION_ID AND T4.ROLE_ID= ? WHERE T2.TYPE = '2' " +
				"AND T2.MODULE_ID IN (SELECT ID FROM SYS_MODULE WHERE STATUS='1') ORDER BY ORDER_INDEX ASC";
		List<Map<String, Object>> list = sysRoleDao.getJdbcTemplate().queryForList(sql, Long.valueOf(roleId), Long.valueOf(roleId));
		for (Map<String, Object> map : list) {
			if(roleId.equals(map.get("ROLE_ID")!=null?map.get("ROLE_ID").toString():"")){
				map.put("checked", true);
			}
			map.remove("ROLE_ID");
			map.put("open", true);
		}
		String json = JsonUtil.toJson(list);
		return json;
	}

	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class, readOnly=false)
	@OperationDescription(operateType = "saveRoleModuleFun", content = "角色授权信息\n角色ID:${#roleId}\n模块ID:${#moduleIds}\n功能ID:${#funcIds}", operateObj = "SysRole")
	public boolean saveRoleModuleFun(Long roleId, String moduleIds, String funcIds) throws Exception{
		boolean result = true;
		QueryCondition queryCondition = new QueryCondition();
		QueryBean qb = new QueryBean(" WHERE ROLE_ID = ?", "ROLE_ID", roleId);
		queryCondition.setQueryBean(qb);
		String[] moduleArr = StringUtils.split(moduleIds, ",");
		String[] funcArr = StringUtils.split(funcIds, ",");
		List<SysRoleModule> roleModuleList = new LinkedList<SysRoleModule>();
		List<SysRoleFunction> roleFunctionList = new LinkedList<SysRoleFunction>();
		Long roleIdL = Long.valueOf(roleId);
		for (int i = 0; i < moduleArr.length; i++) {
			Long id = Long.valueOf(moduleArr[i]);
			SysRoleModule roleModule = new SysRoleModule();
			roleModule.setRoleId(roleIdL);
			roleModule.setModuleId(id);
			roleModuleList.add(roleModule);
		}
		for (int i = 0; i < funcArr.length; i++) {
			Long id = Long.valueOf(funcArr[i]);
			SysRoleFunction roleFunction = new SysRoleFunction();
			roleFunction.setRoleId(roleIdL);
			roleFunction.setFunctionId(id);
			roleFunctionList.add(roleFunction);
		}
		try {
			sysRoleModuleDao.delete(queryCondition);
			sysRoleFunctionDao.delete(queryCondition);
			if(roleModuleList!=null && !roleModuleList.isEmpty()){
				sysRoleModuleDao.batchSave(roleModuleList);
			}
			if(roleFunctionList!=null && !roleFunctionList.isEmpty()){
				sysRoleFunctionDao.batchSave(roleFunctionList);
			}
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
			result = false;
			throw new ServiceException("授权角色出错!["+e.getMessage()+"]");
		}
		return result;
	}

}
